package com.practice.util;

import java.util.ArrayList;

import com.practice.util.FileHelper;

public class Tree {
	private Node root;
	
	public Tree(Node root) {
		this.root = root;
	}
	
	public Node getRoot() {
		return this.root;
	}
	
	public static Tree create(int[] tree) {
		int N = tree.length;
		Node[] nodes = new Node[tree.length];
		for (int i=0; i<N; i++) {
			nodes[i] = new Node(i);
		}
		
		for (int i=0; i<N-1; i++) {
			nodes[tree[i]].addNode(nodes[i]);
		}
		
		return new Tree(nodes[N-1]);
	}
	
	public static Tree create(String file) {
		ArrayList<Node>	current = new ArrayList<Node>();
		String[] lines = FileHelper.readFile(file).split("\n");
		Node root = new Node(atoi(lines[0]));
		current.add(root);
		
		for (int i=1; i<lines.length; i++) {
			int level = 0;
			while (lines[i].charAt(level) == '\t') level++;
			
			Node node = new Node(atoi(lines[i]));
			Node parent = current.get(level-1);
			parent.addNode(node);
			
			if (current.size() <= level) {
				current.add(node);
			}
			else {
				current.set(level, node);
			}
		}
		
		return new Tree(root);
	}
	
	public void indented() {
		printIndentedNode(getRoot(), 0);
	}
	
	private void printIndentedNode(Node node, int level) {
		for (int i=0; i<level; i++) {
			System.out.print("  ");
		}
		
		System.out.println(node.value());
		
		for (Node child : node.getChildren()) {
			printIndentedNode(child, level+1);
		}
	}
	
	private static int atoi(String str) {
		return Integer.parseInt(str.trim());
	} 
	
	public static void main(String[] args) {
		int[] a = new int[]{15, 13, 15, 11, 11, 15, 15, 13, 13, 13, 19, 27, 15,
				22, 19, 27, 19, 19, 19, 20, 22, 22, 23, 27, 26, 26, 27, -1};
		Tree tree = Tree.create(a);
		tree.indented();
	}
}
